package pt.utl.ist.calcNotas;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;


public class CadeiraFantastica extends Activity {
    final Context context = this;
    private Activity act = this;
    private ArrayList<Cadeira> cadeiras;
    private int id;
    private Cadeira c;
    private FantasticAdapter fa;
    private ListView lv;
    private static Toast falta;


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.cadeira_fantastica_layout);
        Intent i = getIntent();
        cadeiras = (ArrayList<Cadeira>)i.getSerializableExtra("cadeiras");
        id = i.getIntExtra("id", 0);
        c = cadeiras.get(id);
        this.setTitle(c.getNome());
        fa = new FantasticAdapter(this, this.getApplicationContext(), c.getElementos(), cadeiras);
        lv = (ListView)findViewById(R.id.expandableListView);
        lv.setAdapter(fa);
        falta= Toast.makeText(this,"Faltam componentes!!!",Toast.LENGTH_SHORT);

        calculaNota();




        Button btn = (Button)findViewById(R.id.addElemento);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newElementoFantastico();
            }
        });
    }


    public void newElementoFantastico(){

        LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        AlertDialog.Builder bu = new AlertDialog.Builder(context);
        final View dialogView=inflater.inflate(R.layout.elemento_fantastico,null);
        bu.setView(dialogView);

        final AlertDialog dialog;

        bu.setTitle(R.string.novotitulo);
        bu.setPositiveButton("Inserir",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialo, int which) {
                String nome = ((EditText)dialogView.findViewById(R.id.editNome)).getText().toString();
                Integer peso=((SeekBar)dialogView.findViewById(R.id.seekBar)).getProgress();
                Boolean notaM=((Switch)dialogView.findViewById(R.id.switch1)).isChecked();
                if(notaM){
                 Integer notaMinima =((SeekBar)dialogView.findViewById(R.id.seekBar2)).getProgress();

                c.getElementos().add(new Elemento(nome,peso,notaMinima));
                }
                else{
                    c.getElementos().add(new Elemento(nome,peso));
                }
                Toast.makeText(context, "Componente " + nome + " inserido!",
                        Toast.LENGTH_LONG).show();
                fa.notifyDataSetChanged();
                calculaNota();
                SaveData();

            }
        })
                .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialo, int which) {
                        Toast.makeText(context, "Novo componente cancelado!",
                                Toast.LENGTH_LONG).show();
                        dialo.cancel();
                    }
                });


        dialog=bu.create();


        final LinearLayout mini=(LinearLayout)dialogView.findViewById(R.id.LayoutMinima);

        mini.setVisibility(View.GONE);

        SeekBar slb = (SeekBar)dialogView.findViewById(R.id.seekBar);
        slb.setMax(c.pesoRestante());
        slb.setProgress(0);
        ((TextView)dialogView.findViewById(R.id.textViewPeso)).setText("0%");
        slb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                TextView txt = (TextView)dialog.findViewById(R.id.textViewPeso);
                txt.setText(i+"%");
                calculaNota();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }
        });

        Switch sw =(Switch)dialogView.findViewById(R.id.switch1);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mini.setVisibility(View.VISIBLE);
                }else
                {
                    mini.setVisibility(View.GONE);
                    SeekBar slb2 = (SeekBar)dialogView.findViewById(R.id.seekBar2);
                    slb2.setProgress(0);
                    ((TextView)dialogView.findViewById(R.id.textNotaMinima)).setText("0 Valores");
                }
            }
        });
        SeekBar slb2 = (SeekBar)dialogView.findViewById(R.id.seekBar2);
        slb2.setMax(200);
        slb2.setProgress(0);
        ((TextView)dialogView.findViewById(R.id.textNotaMinima)).setText("0 Valores");
        slb2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                TextView txt = (TextView)dialog.findViewById(R.id.textNotaMinima);
                txt.setText(i/10f+"Valores");
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }
        });
        dialog.show();
    }

    public void editElementoFantastico(int id){
        LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        AlertDialog.Builder bu = new AlertDialog.Builder(context);
        final View dialogView=inflater.inflate(R.layout.elemento_fantastico,null);
        bu.setView(dialogView);
        final Elemento el = c.getElementos().get(id);

        final AlertDialog dialog;

        int peso = el.getPeso();
        boolean b = el.notaMinimaB;

        ((EditText)dialogView.findViewById(R.id.editNome)).setText(el.getNome());
        ((TextView)dialogView.findViewById(R.id.textViewPeso)).setText(peso + "%");
        ((Switch)dialogView.findViewById(R.id.switch1)).setChecked(b);
        SeekBar sb = ((SeekBar)dialogView.findViewById(R.id.seekBar2));
        final LinearLayout mini=(LinearLayout)dialogView.findViewById(R.id.LayoutMinima);
        if(b){
            mini.setVisibility(View.VISIBLE);
            sb.setProgress(el.notaMinima);
            ((TextView)dialogView.findViewById(R.id.textNotaMinima)).setText(el.notaMinima/10f+"Valores");
        }
         else{
            mini.setVisibility(View.GONE);
        }

        bu.setTitle(R.string.editTu);
        bu.setPositiveButton("Actualizar",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialo, int which) {
                String nome = ((EditText)dialogView.findViewById(R.id.editNome)).getText().toString();
                el.setNome(nome);
                el.setPeso(((SeekBar) dialogView.findViewById(R.id.seekBar)).getProgress());
                el.setNotaMinimaB(((Switch) dialogView.findViewById(R.id.switch1)).isChecked());
                el.setNotaMinima(((SeekBar)dialogView.findViewById(R.id.seekBar2)).getProgress());
                Toast.makeText(context, "Componente " + nome + " actualizado!",
                        Toast.LENGTH_LONG).show();
                fa.notifyDataSetChanged();
                calculaNota();
                SaveData();
            }
        })
                .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialo, int which) {
                        Toast.makeText(context, R.string.edicaoCancel,
                                Toast.LENGTH_LONG).show();
                    }
                });


        dialog=bu.create();

        SeekBar slb = (SeekBar)dialogView.findViewById(R.id.seekBar);
        slb.setMax(c.pesoRestante()+peso);
        slb.setProgress(peso);
        slb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                TextView txt = (TextView)dialog.findViewById(R.id.textViewPeso);
                txt.setText(i+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }
        });

        Switch sw =(Switch)dialogView.findViewById(R.id.switch1);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mini.setVisibility(View.VISIBLE);
                }else
                {
                    mini.setVisibility(View.GONE);
                    SeekBar slb2 = (SeekBar)dialogView.findViewById(R.id.seekBar2);
                    slb2.setProgress(0);
                    ((TextView)dialogView.findViewById(R.id.textNotaMinima)).setText("0 Valores");
                }
            }
        });
        SeekBar slb2 = (SeekBar)dialogView.findViewById(R.id.seekBar2);
        slb2.setMax(200);
        slb2.setProgress(0);
        slb2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                TextView txt = (TextView)dialog.findViewById(R.id.textNotaMinima);
                txt.setText(i/10f+"Valores");
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //SERIALIZATION NOW!!!
            }
        });
        dialog.show();
    }

    protected void SaveData(){
        try
        {
            String path = this.getApplicationContext().getFilesDir() + "/storage/";
            File file = new File(path);
            file.mkdirs();
            path+="cadeiras.sav";
            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(path, false));
            oos.writeObject(cadeiras);
            oos.flush();
            oos.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void removeElemento(final int i){
        final String s = c.elementos.get(i).getNome();
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setMessage("Tem a certeza que deseja eliminar "+ s +"?")
                .setPositiveButton("Eliminar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int a) {
                        c.elementos.remove(i);
                        Toast.makeText(context, s + " eliminado!",
                                Toast.LENGTH_LONG).show();
                        fa.notifyDataSetChanged();
                        calculaNota();
                        SaveData();
                    }
                })
                .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(context, R.string.cancelar,
                                Toast.LENGTH_LONG).show();
                    }
                });

        b.create().show();
    }

    public void guardaNota(int i, int nota){
        c.elementos.get(i).setValor(nota-c.elementos.get(i).getNotaMinima());
        fa.notifyDataSetChanged();
        calculaNota();
        SaveData();
    }

    public void calculaNota(){
        double fantastico = 0;
       if(c.pesoRestante()>0){
           ((TextView)findViewById(R.id.NotaFinal)).setText("Nota Final: ");
           LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutNota);
           ll.setBackgroundResource(R.color.negativa);
            falta.show();

           Button btn = (Button)findViewById(R.id.addElemento);
           btn.setVisibility(View.VISIBLE);
           return;
       }

        falta.cancel();
        Button btn = (Button)findViewById(R.id.addElemento);
        btn.setVisibility(View.GONE);


        for (Elemento e:c.elementos){
            fantastico += (e.getPeso()/100f)*(e.getValor()/10f);

        }
        int a = (int) Math.round(fantastico);
        ((TextView)findViewById(R.id.NotaFinal)).setText("Nota Final: "+a);
        LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutNota);
        if(a>=10)ll.setBackgroundResource(R.color.positiva);
        else ll.setBackgroundResource(R.color.negativa);
    }

}